package com.npy.reggie.contorller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.npy.reggie.doman.R;
import com.npy.reggie.doman.Setmeal;
import com.npy.reggie.doman.SetmealDish;
import com.npy.reggie.dto.SetmealDto;
import com.npy.reggie.service.CategoryService;
import com.npy.reggie.service.SetmealDishService;
import com.npy.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {

    @Autowired
    private SetmealService setmealService ;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R<String> saveSetmeal(@RequestBody SetmealDto setmealDto){
        log.info("setmeal接收到的数据{}",setmealDto.toString());
        setmealService.saveWithSetmealDish(setmealDto);
        return R.success("添加成功");
    }
    @GetMapping("/page")
    public R<Page<SetmealDto>> pageSetmealDto(int page , int pageSize , String name ){

        Page<Setmeal> pageInfo = new Page<>(page,pageSize);
        pageInfo = setmealService.page(pageInfo, new QueryWrapper<Setmeal>()
                .lambda().eq(name != null, Setmeal::getName, name));

        Page<SetmealDto> setmealDtoPage = new Page<>();

        BeanUtils.copyProperties(pageInfo,setmealDtoPage,"records");

        List<SetmealDto> collect = pageInfo.getRecords().stream().map(item -> {
            SetmealDto setmealDto = new SetmealDto();

            setmealDto.setCategoryName(categoryService.getById(item.getCategoryId()).getName());

            BeanUtils.copyProperties(item,setmealDto);

            return setmealDto;
        }).collect(Collectors.toList());

        setmealDtoPage.setRecords(collect);

        return R.success(setmealDtoPage);

    }

    @DeleteMapping
    //@RequestParam
    public R<String> deleteSetMeal(@RequestParam("ids") List<Long> id){
        log.info("setmeal{}", id);

        setmealService.removeWithSteamDish(id);

        return R.success("sada");
    }

    @GetMapping("/list")
    public R<List<Setmeal>> listSetmeal(Setmeal setmeal){

        log.info("Setmeal--------- {}",setmeal);

        QueryWrapper<Setmeal> queryWrapper = new QueryWrapper<>();

        queryWrapper.lambda().eq(setmeal.getCategoryId()!=null,Setmeal::getCategoryId,setmeal.getCategoryId())
                .eq(setmeal.getStatus()!=null,Setmeal::getStatus,setmeal.getStatus());

        return R.success(setmealService.list(queryWrapper));

    }
}
